package config;


import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Description: TODO
 * @Author 50705 2020/1/7
 **/
public class AsyncTaskExecutor {

    /**
     * 核心线程数
     */
    private static final int DEFAULT_CORE_SIZE=10;

    /**
     * 最大线程数
     */
    private static final int MAX_QUEUE_SIZE=50;

    /**
     * 线程池对象
     */
    private volatile static ThreadPoolExecutor executor;

    private AsyncTaskExecutor() {}

    /**
     * 获取单例的线程池对象
     * */
    public static ThreadPoolExecutor getInstance() {
        if (executor == null) {
            synchronized (AsyncTaskExecutor.class) {
                if (executor == null) {
                    ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                            .setNameFormat("pool-%d").build();
                    executor = new ThreadPoolExecutor(DEFAULT_CORE_SIZE, MAX_QUEUE_SIZE,
                            Integer.MAX_VALUE, TimeUnit.MILLISECONDS,
                            new LinkedBlockingDeque<Runnable>(1024), namedThreadFactory,
                            new ThreadPoolExecutor.AbortPolicy()
                    );
                }
            }
        }
        return executor;
    }

    public void execute(Runnable runnable) {
        if (runnable == null) {
            return;
        }
        executor.execute(runnable);
    }

    /**
     * 从线程队列中移除对象
     * */
    public void cancel(Runnable runnable) {
        if (executor != null) {
            executor.getQueue().remove(runnable);
        }
    }

}
